package com.intelligent.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.intelligent.pojo.CustomerInfo;
import com.intelligent.pojo.CustomerManagement;
import com.intelligent.pojo.TUser;
import com.intelligent.service.CustomerInfoService;
import com.intelligent.service.CustomerManagementService;
import com.intelligent.service.TUserService;
import com.intelligent.utils.Result;
import com.intelligent.vo.CustomerPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/customer")
public class SaleCustomerController {

    @Autowired
    private CustomerManagementService customerManagementService;

    @Autowired
    private CustomerInfoService customerInfoService;

    @Autowired
    private TUserService tUserService;

    // 分页查询（按客户名称、联系人、状态筛选）
    @PostMapping("/page")
    public Result<Page<CustomerManagement>> pageList(@RequestBody CustomerPage customerPage) {
        Page<CustomerManagement> page = new Page<>(customerPage.getPageNum(), customerPage.getPageSize());
        LambdaQueryWrapper<CustomerManagement> wrapper = new LambdaQueryWrapper<>();
        if (customerPage.getCustomerName() != null && !customerPage.getCustomerName().isEmpty()) {
            wrapper.like(CustomerManagement::getCustomerName, customerPage.getCustomerName());
        }

        wrapper.orderByDesc(CustomerManagement::getId);

        Page<CustomerManagement> result = customerManagementService.page(page, wrapper);

        // 关联用户表获取联系人姓名
        if (result.getRecords() != null && !result.getRecords().isEmpty()) {
            List<Long> userIds = result.getRecords().stream()
                .map(CustomerManagement::getUId)
                .filter(uId -> uId != null)
                .distinct()
                .collect(Collectors.toList());

            if (!userIds.isEmpty()) {
                LambdaQueryWrapper<TUser> userWrapper = new LambdaQueryWrapper<>();
                userWrapper.in(TUser::getUserId, userIds);
                List<TUser> users = tUserService.list(userWrapper);
                Map<Long, String> userMap = users.stream()
                    .collect(Collectors.toMap(TUser::getUserId, TUser::getRealName));
                result.getRecords().forEach(customer -> {
                    if (customer.getUId() != null) {
                        customer.setContactPersonName(userMap.get(customer.getUId()));
                    }
                });
            }
        }
        return Result.success(result);
    }

    // 新建客户
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public Result<CustomerManagement> create(@RequestBody CustomerManagement customerManagement) {
        if (customerManagement.getStatus() == null) {
            customerManagement.setStatus(0);
        }
        boolean saved = customerManagementService.save(customerManagement);
        if (!saved) {
            return Result.error("保存失败");
        }
        String yearMonth = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
        String idPart = String.format("%04d", customerManagement.getId());
        String customerCode = "KH" + yearMonth + idPart;
        customerManagement.setCustomerCode(customerCode);
        boolean updated = customerManagementService.updateById(customerManagement);
        if (!updated) {
            return Result.error("写入客户编号失败");
        }
        return Result.success(customerManagement);
    }

    // 客户详情（含联系人姓名）
    @GetMapping("/{id}")
    public Result<CustomerManagement> detail(@PathVariable Long id) {
        CustomerManagement customerManagement = customerManagementService.getById(id);
        if (customerManagement == null) {
            return Result.error("未找到数据");
        }
        if (customerManagement.getUId() != null) {
            TUser user = tUserService.getById(customerManagement.getUId());
            if (user != null) {
                customerManagement.setContactPersonName(user.getRealName());
            }
        }
        return Result.success(customerManagement);
    }

    // 根据 customer_info 的 customer_id 关联查询客户对账信息
    @GetMapping("/{id}/info")
    public Result<CustomerInfo> infoByCustomer(@PathVariable Long id) {
        LambdaQueryWrapper<CustomerInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerInfo::getCustomerId, id);
        CustomerInfo info = customerInfoService.getOne(wrapper, false);
        return Result.success(info);
    }
}


